package com.nehc.nettyserver.service.impl;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.StpUtil;
import com.nehc.nettyserver.service.UserAuthService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户认证服务实现类
 * 
 * @author NEHC
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class UserAuthServiceImpl implements UserAuthService {

    private final JdbcTemplate jdbcTemplate;
    
    @Override
    public Map<String, Object> login(String username, String password) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 查询用户
            String sql = "SELECT * FROM sys_user WHERE username = ? AND deleted = 0";
            List<Map<String, Object>> users = jdbcTemplate.queryForList(sql, username);
            
            if (users.isEmpty()) {
                result.put("success", false);
                result.put("message", "用户不存在");
                return result;
            }
            
            Map<String, Object> user = users.get(0);
            
            // 验证密码
            String storedPassword = (String) user.get("password");
            String salt = (String) user.get("salt");
            String encryptedPassword = SaSecureUtil.md5(password + salt);
            
            if (!encryptedPassword.equals(storedPassword)) {
                result.put("success", false);
                result.put("message", "密码错误");
                return result;
            }
            
            // 获取用户ID
            String userId = user.get("id").toString();
            
            // Sa-Token登录
            StpUtil.login(userId);
            
            // 获取token
            String tokenValue = StpUtil.getTokenValue();
            
            // 移除敏感信息
            user.remove("password");
            user.remove("salt");
            
            // 添加用户权限和角色信息
            List<String> permissions = getUserPermissions(userId);
            List<String> roles = getUserRoles(userId);
            
            result.put("success", true);
            result.put("message", "登录成功");
            result.put("token", tokenValue);
            result.put("user", user);
            result.put("permissions", permissions);
            result.put("roles", roles);
            
        } catch (Exception e) {
            log.error("登录失败", e);
            result.put("success", false);
            result.put("message", "登录失败: " + e.getMessage());
        }
        
        return result;
    }

    @Override
    public boolean register(String username, String password, String nickname) {
        try {
            // 检查用户名是否已存在
            String checkSql = "SELECT COUNT(*) FROM sys_user WHERE username = ?";
            Integer count = jdbcTemplate.queryForObject(checkSql, Integer.class, username);
            
            if (count != null && count > 0) {
                return false;
            }
            
            // 生成盐值
            String salt = SaSecureUtil.md5(username + System.currentTimeMillis());
            
            // 加密密码
            String encryptedPassword = SaSecureUtil.md5(password + salt);
            
            // 插入用户
            String insertSql = "INSERT INTO sys_user (username, password, salt, nickname, create_time) VALUES (?, ?, ?, ?, ?)";
            int rows = jdbcTemplate.update(insertSql, username, encryptedPassword, salt, nickname, System.currentTimeMillis());
            
            return rows > 0;
            
        } catch (Exception e) {
            log.error("注册用户失败", e);
            return false;
        }
    }

    @Override
    public void logout(String userId) {
        StpUtil.logout(userId);
    }

    @Override
    public boolean hasPermission(String userId, String permission) {
        List<String> permissions = getUserPermissions(userId);
        return permissions.contains(permission) || permissions.contains("*");
    }

    @Override
    public boolean hasRole(String userId, String role) {
        List<String> roles = getUserRoles(userId);
        return roles.contains(role) || roles.contains("admin");
    }

    @Override
    public String getCurrentUserId() {
        return StpUtil.isLogin() ? StpUtil.getLoginIdAsString() : null;
    }

    @Override
    public Map<String, Object> getCurrentUserInfo() {
        String userId = getCurrentUserId();
        if (userId == null) {
            return new HashMap<>();
        }
        
        try {
            String sql = "SELECT * FROM sys_user WHERE id = ? AND deleted = 0";
            List<Map<String, Object>> users = jdbcTemplate.queryForList(sql, userId);
            
            if (users.isEmpty()) {
                return new HashMap<>();
            }
            
            Map<String, Object> user = users.get(0);
            
            // 移除敏感信息
            user.remove("password");
            user.remove("salt");
            
            // 添加用户权限和角色信息
            user.put("permissions", getUserPermissions(userId));
            user.put("roles", getUserRoles(userId));
            
            return user;
            
        } catch (Exception e) {
            log.error("获取当前用户信息失败", e);
            return new HashMap<>();
        }
    }
    
    /**
     * 获取用户权限列表
     */
    private List<String> getUserPermissions(String userId) {
        try {
            String sql = "SELECT p.permission_code FROM sys_user_permission up " +
                    "JOIN sys_permission p ON up.permission_id = p.id " +
                    "WHERE up.user_id = ? AND p.status = 1";
            return jdbcTemplate.queryForList(sql, String.class, userId);
        } catch (Exception e) {
            log.error("获取用户权限失败", e);
            return List.of();
        }
    }
    
    /**
     * 获取用户角色列表
     */
    private List<String> getUserRoles(String userId) {
        try {
            String sql = "SELECT r.role_code FROM sys_user_role ur " +
                    "JOIN sys_role r ON ur.role_id = r.id " +
                    "WHERE ur.user_id = ? AND r.status = 1";
            return jdbcTemplate.queryForList(sql, String.class, userId);
        } catch (Exception e) {
            log.error("获取用户角色失败", e);
            return List.of();
        }
    }
} 